<?php
namespace Home\Controller;

use Think\Controller;

class OrdersController extends CommonController
{

  protected $this_table = "orders";

  public function __construct()
  {
    parent::__construct();
    $this->check_login();
  }

  /**
   * [创建订单]
   * @return [type] [description]
   */
  public function create()
  {
    /**
     * 订单数据提交格式，json
     * {shop_id: 0, products: [{id, name, price, num, spec}]}
     * @var [type]
     */
    $payload = file_get_contents('php://input');
    $data = json_decode($payload, true);
    if($data['shop_id']){
      $this->shop_id = $data['shop_id'];
      $this->shops_close();
    }
    foreach($data['products'] as $k=>$v){
      $cate = M('products')->where("id=$v[id] and $data[shop_id]")->find();
      if(!$cate || $cate['status']!=1){
        return_data("error",'products.status,shop_id');
      }
    }
    if ($data['address_id']) {
      $where['id'] = $data['address_id'];
      $where['user_id'] = $this->user_id;
      $field = "receiver_name,receiver_mobile,province,city,area,addr";
      $address = M('addresses')->field($field)->where($where)->find();
      if (!$address) {
        return_data("error", "address.error");
      }
    }

    if ($data['user_coupon_id']) {
      $coupon_check = D("orders")->check_coupon($data['user_coupon_id'], $data['shop_id'], $this->user_id);
      if ($coupon_check['success'] == false) {
        return_data("error", 'order.check_coupon.error', $coupon_check);
      }
      $data['coupon_amount'] = $coupon_check['coupon']['amount'];
    } else {
      $data['coupon_amount'] = 0;
      $data['user_coupon_id'] = 0;
    }

    if (empty($data['products'])) {
      return_data("error", "cart.products.empty");
    }
    $is_platform = false;
    //TODO:库存检查
    foreach ($data['products'] as $key => $value) {
      $product = M("products")->where("id=$value[id]")->Field("stock, is_platform, zan_price, is_limit,product_num,pf_id")->find();

        if (!empty($value['specs'])) {
          foreach ($value['specs'] as $k1 => $v1) {
            if ($v1['num'] > 0 && $v1['num'] >$v1['stock']) {
              return_data("error", "product.num.error");
            }
          }
        }else{
          if($product['is_platform']==1 && $product['pf_id']>0){
            $goods = M("products")->where("id=$product[pf_id]")->find();
            if($v['num'] > $goods['product_num']){
              return_data("error", "product.num.error");
            }
          }else{
            if($v['num'] > $product['product_num']){
                return_data("error", "product.num.error");
            }            
          }

        }


      //目前仅支持单品
      if ($value['price'] == $product['zan_price']) {
        $user_zan = M('zan_product_users')->where("product_id = $value[id] and user_id = {$this->user_id}")->find();
        if ($user_zan && $user_zan['win_no'] && $user_zan['order_id'] && $value['num'] > 1) {
          return_data("error", "cart.products.zan_buy_num.error", $value['id']);
        }
      }
      if ($product['is_platform'] == 1) {
        $is_platform = true;
      }
      if ($product['is_limit'] > 0) {
        if (empty($value['specs'])) {
          $buyed_num = M('order_children')->alias('oc')
            ->join("left join ".C('DB_PREFIX')."orders o on o.id=oc.order_id")
            ->join("left join ".C('DB_PREFIX')."users u on u.id=o.user_id")
            ->where("oc.product_id = {$value['id']} and u.id = {$this->user_id} and o.status not in (3,8)")
            ->sum('product_num');
          if (($buyed_num + $value['num']) > $product['is_limit']) {
            return_data("error", "cart.products.limit", "{$value['id']}/{$value['num']}/{$buyed_num}");
          }
        } else {
          foreach ($value['specs'] as $spec) {
            if ($spec['num'] > 0) {
              $buyed_num = M('order_children')->alias('oc')
                ->join("left join ".C('DB_PREFIX')."orders o on o.id=oc.order_id")
                ->join("left join ".C('DB_PREFIX')."users u on u.id=o.user_id")
                ->where("oc.product_id = {$value['id']} and product_spec = '{$spec['name']}' and u.id = {$this->user_id} and o.status not in (3,8)")
                ->sum('product_num');
              if (($buyed_num + $spec['num']) > $product['is_limit']) {
                return_data("error", "cart.products.limit", $value['id']);
              }
            }
          }
        }
      }
    }

    if (!$data['delivery_amount']) {
      $data['delivery_amount'] = '0.0';
    }
    if (!$data['delivery_types']) {
      $data['delivery_types'] = '1';
    }

    if (isset($data['appointment_time'])) {
      $data['appointment_time'] = strtotime($data['appointment_time']);
    } else {
      $data['appointment_time'] = 0;
    }

    if (!$data['people']) {
      $data['people'] = 0;
    }

    $model = M($this->this_table);
    //点餐--收货地址--配送方式 暂时不填
    //TODO: 价格计算
    $order = array(
      "tran_no" => D("orders")->create_tran_no(),
      "total_amount" => '0.0',
      "delivery_amount" => $data['delivery_amount'],
      "delivery_types" => $data['delivery_types'],
      "delivery_free" => $data['delivery_free'],
      "coupon_amount" => $data['coupon_amount'],
      "user_coupon_id" => $data['user_coupon_id'],
      "threshold" => $data['threshold'],
      "threshold_rebate" => $data['threshold_rebate'],
      "status"=> 1,
      "delivery_status" => '1',
      "user_id" => $this->user_id,
      "shop_id" => $data['shop_id'],
      "seat" => $data['seat'],
      "remark" => trim($data['remark']),
      "point_id" => 0,   //自提点
      "arrived_at" => 0, //预计到达时间
      "created_at" => $this->current_time,
      "updated_at" => $this->current_time,
      "form_id" => $data['form_id'],
      "appointment_time" => $data['appointment_time'],
      "people" => $data['people']
     );
    if ($address) {
      $order = array_merge($order, $address);
    }

    if ($data['delivery_types'] == 3) {
      $order['receiver_name'] = $data['receiver_name'];
      $order['receiver_mobile'] = $data['receiver_mobile'];
    }

    if ($is_platform) {
      $order['app_id'] = $this->app_id;
      $order['is_platform'] = 1;
    }

    //创建 order
    $model->create($order);
    $order_id = $model->add();
    if (!$order_id) {
      return_data("error", "create.orders.error");
    }

    $total_amount = 0.0;
    $index = 0;
    foreach ($data['products'] as $key => $value) {
      if ($value['id']) {
        if (empty($value['specs'])) {
          $products[$index]['product_name'] = $value['name'];
          $products[$index]['product_price'] = $value['price'];
          $products[$index]['proxy_price'] = $value['proxy_price'];
          $products[$index]['product_num'] = $value['num'];
          $products[$index]['product_id'] = $value['id'];
          $products[$index]['product_logo'] = $value['logo'];
          $products[$index]['product_spec'] = '';
          $products[$index]['spec_id'] = 0;

          $products[$index]['order_id'] = $order_id;
          $products[$index]['created_at'] = $this->current_time;

          $total_amount += $value['price'] * $value['num'];
          $index++;
        } else {
          foreach ($value['specs'] as $k => $v) {
            if ($v['num'] > 0) {
              $products[$index]['product_name'] = $value['name'];
              $products[$index]['product_id'] = $value['id'];
              $products[$index]['product_logo'] = $value['logo'];
              $products[$index]['product_price'] = $v['price'];
              $products[$index]['product_num'] = $v['num'];
              $products[$index]['product_spec'] = $v['name'];
              $products[$index]['spec_id'] = $v['id'];

              $products[$index]['order_id'] = $order_id;
              $products[$index]['created_at'] = $this->current_time;

              $total_amount += $v['num'] * $v['price'];
              $index++;
            }
          }
        }
      }
    }
    if ($data['threshold_rebate'] && $data['threshold_rebate'] > 0) {
      $total_amount = $total_amount - $data['threshold_rebate'];
    }

    if ($data['delivery_amount'] && $data['delivery_free'] == 0) {
      $total_amount = $total_amount + $data['delivery_amount'];
    }
    $total_amount = $total_amount - $data['coupon_amount'];
    M('orders')->where("id=$order_id")->save(array('total_amount' => $total_amount));
    foreach ($products as $key => $value) {
      $result = M("order_children")->data($value)->add();
    }

    if (!$result) {
      return_data("error", "create.".$this->this_table.".error");//blank
    } else {
      //减库存
      //D("Orders")->change_stock($order_id);

      //核销点赞购买
      if ($user_zan) {
        M('zan_product_users') -> where("id={$user_zan[id]}") -> save(array('order_id' => $order_id));
      }

      //核销优惠券
      if ($coupon_check) {
        M('user_coupons') -> where("id = {$data['user_coupon_id']}") -> save(array('status'=>2));
        M('coupons') -> where("id = {$coupon_check['coupon']['id']}") -> save(array('used_num'=>$coupon['coupon']['used_num']+1));
      }

      return_data("success", "create.".$this->this_table.".success", $order_id);
    }
  }

  /**
   * [查看订单]
   * @return [type] [description]
   */
  public function show()
  {
    $model = M($this->this_table);

    //订单号或id查询
    $id = trim(I('id'));
    $tran_no = trim(I('tran_no'));

    if ($id) {
      $where['o.id'] = $id;
    } elseif ($tran_no) {
      $where['o.tran_no'] = $tran_no;
    } else {
      return_data("error", $this->this_table.".id.and.tran_no.blank");
    }

    //商户查看订单
    if ($this->types == 1 && I('is_business')) {
      $this->shops_close();
      $where['o.shop_id'] = $this->shop_id;
    } else {
      $where['o.user_id'] = $this->user_id;
    }

    $fields = "o.*, u.avatar, u.nickname";
    $info = $model->alias('o')
      ->join("left join ".C('DB_PREFIX')."users u on u.id=o.user_id")
      ->field($fields)->where($where)->find();
    // echo $model->getLastSql();exit;
    //无用字段不显示
    unset($info['arrived_at']);//预计送达时间，老订单号
    unset($info['arrived_at']);

    if (empty($info)) {
      return_data("error", "show.".$this->this_table.".empty");//blank
    } else {
      $order_id = $info['id'];
      $info['created_at'] = local_time($info['created_at']);
      $info['appointment_time'] = local_time($info['appointment_time']);
      // if($info['arrived_at']) $info['arrived_at'] = local_time($info['arrived_at']);

      //商品列表
      $field = "id,product_name,product_price,product_num,product_id,product_spec,product_logo";
      $child_list = M("order_children")->field($field)->where("order_id=".$order_id)->order("id asc")->select();
      $info['order_children'] = $child_list?$child_list:array();

      return_data("success", "show.".$this->this_table.".success", $info);
    }
  }

  /**
   * [订单列表]
   * @return [type] [description]
   */
  public function index()
  {
    $model = M($this->this_table);

    $page_index = I("page", 1);
    $page_size = I("size", 10);
    $status = I('status', 0);

    $started_at = trim(I("started_at"));//下单时间
    $ended_at = trim(I("ended_at"));

    //商户查看订单
    if ($this->types == 1 && I('is_business')) {
      $this->shops_close();
      $where = " o.shop_id=".$this->shop_id;
    } else {//下单或发货
      $where = " o.user_id=".$this->user_id;
    }

    $tran_no = I("tran_no");
    if ($tran_no) {
      $where .= " and o.tran_no like '%$tran_no%'";
    }

    if ($started_at) {
      $started_at = strtotime($started_at);
      $where .= " and o.created_at >= '$started_at'";
    }

    if ($ended_at) {
      $ended_at = strtotime($ended_at);
      $where .= " and o.created_at < '$ended_at'";
    }

    if ($status) {
      if ($status == 6) {
        $where .= " and o.status in (5,6,8,9,10)";
      } else {
        $where .= " and o.status = $status";
      }
    }

    //排序
    $order = "o.id desc ";
    $field = "o.*, s.name, s.logo, u.nickname, u.avatar";
    $list = $model->alias("o")
        ->join("left join ".C('DB_PREFIX')."shops s on s.id=o.shop_id")
        ->join("left join ".C('DB_PREFIX')."users u on u.id=o.user_id")
        ->field($field)->where($where)->order($order)->page($page_index.",".$page_size)->select();

    if (empty($list)) {
      return_data("error", "index.".$this->this_table.".empty");
    } else {
      foreach ($list as $key => &$info) {
        //商品列表
        $info['created_at'] = local_time($info['created_at']);
        $info['updated_at'] = local_time($info['updated_at']);

        //无用字段不显示
        unset($info['arrived_at']);//预计送达时间，老订单号
        unset($info['arrived_at']);

        // if($info['arrived_at']) $info['arrived_at'] = local_time($info['arrived_at']);

        //商品列表
        $field = "id,product_name,product_price,product_num,product_id,product_spec,product_logo";
        $child_list = M("order_children")->field($field)->where("order_id=$info[id]")->order("id asc")->select();
        $info['order_children'] = $child_list?$child_list:array();
      }
      return_data("success", "index.".$this->this_table.".success", $list);
    }
  }

  public function notify()
  {
    $this->shops_close();
    if ($this->types != 1) {
      return_data('error', 'order.notify.unauth');
    }

    $payload = file_get_contents('php://input');
    $data = json_decode($payload, true);

    $map = array(
    'o.id' => $data['id'],
    'o.shop_id' => $this->shop_id);
    $data['updated_at'] = $this->current_time;
    $order = M('orders')->alias('o')
      ->join("left join ".C('DB_PREFIX')."users u on u.id=o.user_id")
      ->join("left join ".C('DB_PREFIX')."shops s on s.id=o.shop_id")
      ->field('o.*,u.xcx_openid, s.name shop_name')
      ->where($map)->find();

    $order_children = M('order_children')->where("order_id={$order['id']}")->select();
    $order_child = $order_children[0];

    $order['body'] = "{$order_child['product_name']}等商品";
    $app_info = $this->app_info;
    $order['template_id'] = $app_info['confirm_order_template_id'];//'-x7TQi7-9vAjn6v7ozxM0q9QW2x1h3BQKe9op1Ysopw';
    $order['status'] = '已确认';
    $order['created_at'] = date('Y-m-d H:i:s', $order['created_at']);

    if ($order['delivery_types'] == 3) {
      $keyword4 = '无';
    } else {
      $keyword4 = "{$order[province]} {$order[city]} {$order[area]} {$order[addr]}";
    }

    $order['data'] = array(
      'keyword1' => array('value' => $order['tran_no'], 'color' => '#173177'),
      'keyword2' => array('value' => $order['total_amount'], 'color' => '#173177'),
      'keyword3' => array('value' => $order['body'], 'color' => '#173177'),
      'keyword4' => array('value' => $keyword4, 'color' => '#173177'),
      'keyword5' => array('value' => "{$order['receiver_name']} / {$order['receiver_mobile']}", 'color' => '#173177'),
      'keyword6' => array('value' => "店家：{$order['shop_name']}", 'color' => '#173177')
      );
    $result = send_app_msg($order, $this->app_id);

    if ($result) {
      #增加销量
      foreach ($order_children as $child) {
        M('products')->where("id = {$child['product_id']}")->setInc('sales', $child['product_num']);
      }
      M('orders')->where("id={$order['id']}")->save(array('is_notify'=>1));
      return_data('success', 'order.notify.success');
    } else {
      return_data('error', 'order.notify.error');
    }
  }

  /**
   * [订单状态更新]
   * @return [type] [description]
   */
  public function status()
  {
    $model = M($this->this_table);

    $payload = file_get_contents('php://input');
    $data = json_decode($payload, true);

    //1:未支付 2:已支付（待发货）；3：已取消；4：已发货 5：已完成
    $status_arr = array(2, 3, 4, 5);
    if (!in_array($data['status'], $status_arr)) {
      return_data("error", $this->this_table.".status.error");
    }

    $map = array(
    'o.id' => $data['id'],
    'o.shop_id' => $this->shop_id);
    $data['updated_at'] = $this->current_time;
    $order = $model->alias('o')
      ->join("left join ".C('DB_PREFIX')."users u on u.id=o.user_id")
      ->join("left join ".C('DB_PREFIX')."shops s on s.id=o.shop_id")
      ->field('o.*,u.xcx_openid, s.name shop_name')
      ->where($map)->find();

    $result = $model->alias('o')->where($map)->save($data);

    if ($result) {
      // if($data['status'] == 6){
      //   $order['status'] = '商家已确认';
      //   $order['created_at'] = date('Y-m-d H:i:s', $order['created_at']);

      //   $result = send_xcx_msg($order);

      //   return_data("success","{$this->this_table}.status.success", $result);
      // }

      return_data("success", "{$this->this_table}.status.success");
    } else {
      return_data("error", "{$this->this_table}.status.error");
    }
  }

  public function express()
  {
    $this->shops_close();
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    $where = array('id' => $data['id'], 'status' => 2);
    $order = M('orders')->where($where)->find();

    if ($order) {
      if (isset($data['exp_company']) && isset($data['exp_no'])) {
        $update_data = array('exp_company' => $data['exp_company'], 'exp_no' => $data['exp_no'], 'status' => 4);
        $app_info = $this->app_info;
        if ($app_info['receive_days'] == 0) {
          $update_data['status'] = 5;
          $update_data['picked_at'] = $this->current_time;
          if ($app_info['aftersale_days'] == 0) {
            $update_data['status'] = 7;
            //TODO: status=4 or status=2
            $item = M('orders')->alias('o')
                     ->where("o.id={$data['id']} and o.status = 2")
                     ->join("left join ".C('DB_PREFIX')."shops sp on sp.id = o.shop_id")
                     ->join("left join ".C('DB_PREFIX')."apps ap on ap.id = sp.app_id")
                     ->field('o.total_amount as total_amount, sp.id as shop_id, ap.id as app_id,ap.aftersale_days as aftersale_days, sp.amount as shop_amount, o.id as order_id')
                     ->find();
                     // echo M('orders')->getLastSql();exit;
            create_amount_log($item);
          }
        };
        $result = M('orders')->where($where)->save($update_data);
        if ($result) {
          $order_child = M('order_children')->where("order_id={$order['id']}")->find();
          $content =  "{$order_child['product_name']} 等商品";
          $order['xcx_openid'] = M('users')->where("id={$order['user_id']}")->getField('xcx_openid');
          $order['template_id'] = $app_info['express_order_template_id'];
          $order['form_id'] = $order['prepay_id'];
          $expressed_at = date('Y-m-d H:i:s', time());
          $addr = "{$order['province']} {$order['city']} {$order['area']} {$order['addr']}";
          $order['data'] = array(
            'keyword1' => array('value' => $content, 'color' => '#173177'),
            'keyword2' => array('value' => $order['tran_no'], 'color' => '#173177'),
            'keyword3' => array('value' => $addr, 'color' => '#173177'),
            'keyword4' => array('value' => $data['exp_company'], 'color' => '#173177'),
            'keyword5' => array('value' => $data['exp_no'], 'color' => '#173177'),
            'keyword6' => array('value' => $expressed_at, 'color' => '#173177')
            );
          $order['page'] = "pages/orders/order?id={$order['id']}";

          $result = send_app_msg($order, $this->app_id);

          return_data('success', 'update.order_exp.success', $result);
        } else {
          return_data('error', 'update.order_exp.error');
        }
      } else {
        return_data('error', 'update.order_exp.exp_blank');
      }
    } else {
      return_data('error', 'update.order_exp.blank');
    }
  }

  public function prepay_id()
  {
    $payload = file_get_contents('php://input');
    $data = json_decode($payload, true);

    $order = M('orders')->where("tran_no={$data['tran_no']}")->find();
    if ($order && $data['prepay_id']) {
      $result = M('orders')->where("id={$order['id']}")->save($data);

      return_data('success', 'update.prepay_id.success', $result);
    } else {
      return_data('error', 'update.prepay_id.error');
    }
  }

  public function receive()
  {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    $where = array(
      'id' => $data['id'],
      'status' => 4
    );
    $order = M('orders')->alias('o')
             ->where("o.id={$data['id']} and o.status=4")
             ->join("left join ".C('DB_PREFIX')."shops sp on sp.id = o.shop_id")
             ->join("left join ".C('DB_PREFIX')."apps ap on ap.id = sp.app_id")
             ->field('o.total_amount as total_amount, sp.id as shop_id, ap.id as app_id,ap.aftersale_days as aftersale_days, sp.amount as shop_amount, o.id as order_id')
             ->find();

    if ($order) {
      $data = array(
        'picked_at' => $this->current_time,
        'updated_at' => $this->current_time,
        'status' => 5);
      if ($order['aftersale_days'] == 0) {
        $data['status'] = 7;
        create_amount_log($order);
      };
      M('orders')->where($where)->save($data);
      return_data('success', 'order.receive.success');
    } else {
      return_data('error', 'order.receive.invalid');
    }
  }

  public function refund()
  {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    $order_id = $data['id'];
    $app_info = $this->app_info;

    //$today = strtotime('today');
    //$picked_at = $today - 3600 * 24 * $app_info['aftersale_days'];

    $where = "id={$order_id} and status in (2,5)";
    $order = M('orders')->where($where)->find();
    if ($order) {
      $data = array(
        'updated_at' => $this->current_time,
        'status' => 6,
        'refund_reason' => $data['reason']);
      M('orders')->where("id={$order_id}")->save($data);

      if ($order['is_platform'] == 1) {
        #生成提醒消息
        $msg = array(
          'app_id' => $this->app_id,
          'user_id' => $this->user_id,
          'order_id' => $order_id,
          'content' => "新的退款申请，订单号{$order['tran_no']}",
          'status' => 0,
          'types' => 5
        );
        $msg['created_at'] = $msg['updated_at'] = $this->current_time;
        M('messages')->add($msg);
      } else {
        $sms_reuslt = send_order_refund_msg_to_shop($order);
      }

      return_data('success', 'order.refund.success', $sms_result);
    } else {
      return_data('error', 'order.receive.invalid');
    }
  }
}
